/*
 * 上海远境文化传媒有限公司 版权所有
 */
package facade.base;

import cache.CacheHelper;
import facade.AppContext;
import facade.open.request.base.AdminUserRequest;
import facade.open.response.base.AdminUserResponse;
import helper.TextHelper;
import jodd.util.RandomString;
import models.base.AdminUser;
import models.base.AdminUserRole;
import models.base.Corp;
import models.base.Role;
import models.constants.DeletedStatus;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.mvc.Scope;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import static helper.BeanHelper.safeSetValue;


/**
 * created by weiwei on 2018-02-26
 * 用户员工Facade.
 */
public class AdminUserFacade {


    //新建
    public static AdminUser create(AdminUserRequest request) {
        AdminUser loginUser = AppContext.currentUser();
        Corp corp = AppContext.currentCorp();

        AdminUser checkUser;
        //判断登录ID唯一
        checkUser = AdminUser.findByLoginName(request.loginName);
        if (checkUser != null) {
            Scope.Flash.current().put("warn", "该登录ID已经存在，请更换登录ID！");
            return null;
        }
        //判断手机号唯一
        checkUser = AdminUser.findByMobile(request.mobile,null);
        if (checkUser != null) {
            Scope.Flash.current().put("warn", "该手机号码已经存在，请更换手机号码！");
            return null;
        }

        //判断 email 唯一
//        if (StringUtils.isNotBlank(request.email)) {
//            checkUser = AdminUser.findByEmail( request.email );
//            if (checkUser != null) {
//                Scope.Flash.current().put("warn", "该邮箱已经存在，请更换邮箱！");
//                return null;
//            }
//
//        }

        AdminUser adminUser = new AdminUser();
        safeSetValue(request.name, value -> adminUser.name = value);
        safeSetValue(request.loginName, value -> adminUser.loginName = value);
        safeSetValue(request.mobile, value -> adminUser.mobile = value);
        safeSetValue(request.email, value -> adminUser.email = value);
        safeSetValue(request.remark, value -> adminUser.remark = value);
        safeSetValue(request.isAdmin, value -> adminUser.isAdmin = value);

        adminUser.corp = corp;



        //初始密码
        adminUser.passwordSalt = RandomString.getInstance().randomAlphaNumeric(30);
        adminUser.password = TextHelper.encryptPassword("abc123", adminUser.passwordSalt);

        adminUser.deleted = DeletedStatus.UN_DELETED;
        adminUser.createdAt = new Date();
        adminUser.createUserId = loginUser != null ? loginUser.getId() : null;
        adminUser.save();

        if (StringUtils.isNotBlank(request.roleId)) {
            AdminUserRole userRole = new AdminUserRole();
            Role role = new Role();
            role.id = request.roleId;
            userRole.role = role;
            userRole.user = adminUser;
            userRole.save();

        }

        return adminUser;

    }


    //修改
    public static AdminUser update(String id, AdminUserRequest request) {
        AdminUser loginUser = AppContext.currentUser(); //获取登录用户

        AdminUser checkUser;
        //判断手机号唯一
        checkUser = AdminUser.findByMobile(request.mobile,id);
        if (checkUser != null) {
            Scope.Flash.current().put("warn", "该手机号码已经存在，请更换手机号码！");
            return null;
        }
        AdminUser adminUser = AdminUser.findOne( id );
        if (adminUser != null) {
            safeSetValue(request.name, value -> adminUser.name = value);
//            safeSetValue(request.loginName, value -> adminUser.loginName = value);
            safeSetValue(request.mobile, value -> adminUser.mobile = value);
            safeSetValue(request.email, value -> adminUser.email = value);
            safeSetValue(request.remark, value -> adminUser.remark = value);
            adminUser.isAdmin = request.isAdmin == null? false:request.isAdmin;

            adminUser.modifyAt = new Date();
            adminUser.modifyUserId = loginUser != null ? loginUser.getId() : null;
            adminUser.save();

            if (StringUtils.isNotBlank(request.roleId)) {

                AdminUserRole userRole = AdminUserRole.findByUserId(id);
                //如果用户已有的角色和前台传递过来的角色ID不一致，则更新用户的角色
                if (userRole != null) {
                    if(!userRole.role.id.equals(request.roleId)){
                        Role role = new Role();
                        role.id = request.roleId;
                        userRole.role = role;
                        userRole.save();
                    }
                } else {
                    userRole = new AdminUserRole();
                    Role role = new Role();
                    role.id = request.roleId;
                    userRole.role = role;
                    userRole.user = adminUser;
                    userRole.save();

                }

            }
        }

        return adminUser;

    }

    //登录检查验证
    public static AdminUser checkForLogin(String login, String password) {

        //可以使用登录名(loginName),手机号码(mobile)

        if (StringUtils.isBlank(login)) {
            Scope.Flash.current().put("warn", "登录名不能为空！");
            return null;
        }

        if (StringUtils.isBlank(password)) {
            Scope.Flash.current().put("warn", "密码不能为空！");
            return null;
        }

        AdminUser adminUser = AdminUser.findByLoginName(login);
        if (adminUser != null && TextHelper.isValidPassword(password, adminUser.password, adminUser.passwordSalt)) {
            return adminUser;
        }
        return null;
    }

    //获取用户配置
    public static Map<String, Object> getUserConfig(AdminUser user) {
        Map<String, Object> configMap = new LinkedHashMap<>();
        if (user == null) {
            return configMap;
        }
        AdminUserResponse response = AdminUserResponse.from(user);

        Role role = new Role();
        role.id = response.roleId;
        role.name = response.roleName;

        configMap.put("id", response.id);
        configMap.put("name", response.name);
        configMap.put("email", response.email);
        configMap.put("mobile", response.mobile);
        configMap.put("corpName", response.corpName);
        configMap.put("status", user.status);
        configMap.put("role", role);


        return configMap;
    }


    /**
     * 按ID得到用户(去掉缓存).
     */
    public static AdminUser getById(String userId) {
        AdminUser theUser = AdminUser.findById(userId);
        if (theUser == null) {
            return null;
        }
        Logger.debug("LOG00380: log theUser.corp to load info." + theUser.corp);
        if (theUser.deleted == DeletedStatus.DELETED) {
            return null;
        }
        return theUser;
    }


// ----------------------- 缓存统一管理 -----------------------

    /**
     * 清除用户的缓存.
     */
    public static void cleanCache(AdminUser user) {
        CacheHelper.delete(getCacheKeyForUser(user.id));
    }

    public static String getCacheKeyForUser(String userId) {
        return "User_V2_" + userId;
    }

}
